﻿using AutoMapper;
using Coldairarrow.Business;
using Coldairarrow.Entity.BTB_StaffUsers;
using Coldairarrow.Util;
using EFCore.Sharding;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.SubApp
{
    public class FrontUserSyncBusiness :BaseBusiness<BTB_StaffUser>, IFrontUserSyncBusiness, ITransientDependency
    {
        readonly IMapper _mapper;
        private ILogger<FrontUserSyncBusiness> _logger;
        public FrontUserSyncBusiness(IDbAccessor db, IMapper mapper, ILogger<FrontUserSyncBusiness> logger) : base(db)
        {
            _mapper = mapper;
            _logger = logger;
        }

       
        public async Task AddDataAsync(BTB_StaffUser input)
        {
            //已存在，则取消插入
            var exists = await Service.GetIQueryable<BTB_StaffUser>().Where(x => x.id.Equals(input.id)).AnyAsync();
            if(exists)
            {
                return;
            }
            BTB_StaffUser custUser = _mapper.Map<BTB_StaffUser>(input);
            await Service.InsertAsync(custUser);
            _logger.LogDebug("同步生成用户成功");
        }

        public bool CheckExists(string id)
        {
            return Service.GetIQueryable<BTB_StaffUser>().Where(x => x.id.Equals(id)).Any();
        }

        public async Task UpdateDataAsync(BTB_StaffUser input)
        {
            var custUser = await Service.GetIQueryable<BTB_StaffUser>().Where(x => x.id.Equals(input.id)).FirstOrDefaultAsync();
            if(custUser != null)
            {
                custUser.phone = input.phone;
                custUser.NickName = input.NickName;
                custUser.HeadType = input.HeadType;
                custUser.Sex = input.Sex;
                custUser.Address = input.Address;
                custUser.HeadPortrait = input.HeadPortrait;
                custUser.Serial = input.Serial;
                custUser.Password = input.Password;
                custUser.User_YQCode = input.User_YQCode;
                custUser.User_BYQCode = input.User_BYQCode;
                custUser.EditTime = input.EditTime;
                custUser.Longitude = input.Longitude;
                custUser.Latitude = input.Latitude;
                custUser.IsRoot = input.IsRoot;
                custUser.HeadType = input.HeadType;
                custUser.State = input.State;
                await Service.UpdateAsync(custUser);
                _logger.LogDebug("同步更新用户成功");
            }
        }
    }
}
